package com.zyx.enhancement.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.zyx.enhancement.service.LocationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.zyx.enhancement.common.HttpClientHelper.getDataOnHttp;
@Slf4j
@Service("locationService")
public class LocationServiceImpl implements LocationService {

    // IP定位接口地址
    @Value("${content-enhancement.location.api.url}")
    private String URL;

    // IP定位接口密钥
    @Value("${content-enhancement.location.api.key}")
    private String KEY;


    @Override
    public String queryCityLocation(String ip) {
        String result = "";

        // 参数列表
        Map<String, String> params = Map.of("key", KEY, "ip", ip);

        // 请求结果
        JSONObject data = getDataOnHttp(URL, params);
        if (data == null) {
            log.error("【IP定位】接口返回 - NULL - ！");
            return result;
        }

        String status = data.getString("status");

        if(status.equals("0")) {
            JSONObject adInfo = data.getJSONObject("result").getJSONObject("ad_info");
            log.info("【IP定位】接口返回RAW:{}", adInfo);
            // 返回adcode
            result = adInfo.getString("adcode");
        }else{
            // 记录错误日志
            log.error("【IP定位】接口报错:[{}] - {}", status, data.getString("message"));
            return result;
        }

        return result;
    }
}